from PIL import Image, ImageDraw, ImageFont
import os
import platform

# --- 配置 ---
# 字体路径：自动适配Windows/macOS/Linux系统，若自定义路径需替换下方对应值
SYSTEM = platform.system()
if SYSTEM == "Windows":
    # Windows默认字体路径（可替换为自己的字体路径，如"C:/Windows/Fonts/simhei.ttf"）
    FONT_PATH = "C:/Windows/Fonts/simhei.ttf"
elif SYSTEM == "Darwin":  # macOS
    # macOS默认字体路径（可替换为"/Library/Fonts/Arial Unicode.ttf"等）
    FONT_PATH = "/Library/Fonts/Songti.ttc"
else:  # Linux（保留原路径，可根据发行版调整）
    FONT_PATH = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"

OUTPUT_DIR = "../add_text/pomeranian_reports"
ZIP_PATH = "../add_text/pomeranian_reports/pomeranian_reports.zip"

os.makedirs(OUTPUT_DIR, exist_ok=True)

# 报表尺寸 (3:4 比例)
WIDTH, HEIGHT = 768, 1024
BACKGROUND_COLOR = (255, 255, 255)  # 白色背景
TEXT_COLOR = (0, 0, 0)  # 黑色文字

# 表格数据
data = [
    ["排名", "颜色（中英文）", "颜色描述（中文）"],
    ["1", "橙色（Orange）", "颜色范围从深锈红色到浓郁的金色，再到浅蜂蜜金色。"],
    ["2", "奶油色（Cream）", "一种极其浅淡的橙色。"],
    ["3", "橙色貂色（Orange Sable）", "身体为橙色，底毛为更浅的橙色或奶油色，针毛尖端为黑色。"],
    ["4", "黑褐色褐色（Black and Tan）", "基底为黑色，在特定部位（如眉毛、口吻、胸部、腿）有褐色斑块。"],
    ["5", "黑色（Black）", "底毛和针毛均为纯黑色。"],
    ["6", "白色（White）", "纯白色，不应有柠檬色或奶油色的阴影。"],
    ["7", "狼貂色（Wolf Sable）", "底毛为灰色，针毛为灰色带黑色尖端。"],
    ["8", "花色（Parti-Color）", "白色为底色，带有其他颜色的斑块，头部有白色条纹为佳。"],
    ["9", "巧克力色（Chocolate）", "浓郁的棕色。"],
    ["10", "奶油貂色（Cream Sable）", "极浅的奶油色底毛，带有貂色（通常为黑色或深色）尖端。"],
    ["11", "蓝色陨石色（Blue Merle）", "黑色基底上带有灰色、蓝色斑块，像大理石花纹。"],
    ["12", "红色（Red）", "深锈红色。"],
    ["13", "巧克力褐（Chocolate and Tan）", "基底为巧克力色，带有褐色斑块。"],
    ["14", "红色貂色（Red Sable）", "深锈红色的底毛，带有貂色（黑色）尖端。"],
    ["15", "三色（Tri-Colored）", "是花色博美，同时身上还带有褐色的斑块图案。"],
    ["16", "蓝色（Blue）", "是黑色的稀释色，呈现灰蓝色，鼻子、眼眶等应为蓝色。"],
    ["17", "蓝色貂色（Blue Sable）", "基底为蓝色，针毛为深蓝色，末端为黑色尖端。"],
    ["18", "蓝褐（Blue and Tan）", "基底为蓝色，带有褐色斑块。"],
    ["19", "巧克力陨石色（Chocolate Merle）", "巧克力色基底上带有浅棕色斑块，形成大理石花纹。"],
    ["20", "海狸色/河狸色（Beaver）", "颜色从浅饼干色到深棕灰色不等，毛发表面有银蓝色光泽。"],
    ["21", "黑虎斑（Black and Brindle）", "底色为金色、红色或橙色，带有强烈的黑色横条纹。"],
    ["22", "巧克力貂色（Chocolate Sable）", "基底为巧克力色，针毛为更深的巧克力色。"],
    ["23", "薰衣草色（Lavender）", "一种灰白色，毛发表面带有粉红-巧克力色调。"],
    ["24", "蓝虎斑（Blue Brindle）", "底色为金色、红色或橙色，带有强烈的蓝色横条纹。"],
    ["25", "陨石褐（Merle and Tan）", "在蓝色陨石色或巧克力陨石色的基础上，还带有褐色斑块。"]
]

# --- 字体设置 ---
try:
    FONT_TITLE = ImageFont.truetype(FONT_PATH, 36)
    FONT_HEADER = ImageFont.truetype(FONT_PATH, 22)
    FONT_BODY = ImageFont.truetype(FONT_PATH, 18)
except IOError:
    print(f"Warning: Font file not found at {FONT_PATH}. Using default font.")
    FONT_TITLE = ImageFont.load_default()
    FONT_HEADER = ImageFont.load_default()
    FONT_BODY = ImageFont.load_default()


# --- 辅助函数 ---
def get_text_size(draw, text, font):
    """使用 textbbox 获取文本尺寸 (width, height)"""
    # textbbox returns (left, top, right, bottom)
    bbox = draw.textbbox((0, 0), text, font=font)
    width = bbox[2] - bbox[0]
    height = bbox[3] - bbox[1]
    return width, height


def wrap_text(draw, text, font, max_width):
    """根据最大宽度自动换行文本"""
    lines = []
    if not text:
        return [""]

    words = list(text)
    current_line = ""
    for word in words:
        # 使用 textbbox 获取文本尺寸
        width, _ = get_text_size(draw, current_line + word, font)

        if width <= max_width:
            current_line += word
        else:
            lines.append(current_line)
            current_line = word

    lines.append(current_line)
    return [line.strip() for line in lines if line.strip()]


# --- 主生成函数 ---
def generate_report_image(title, rows, file_name):
    img = Image.new('RGB', (WIDTH, HEIGHT), color=BACKGROUND_COLOR)
    draw = ImageDraw.Draw(img)

    # --- 标题 ---
    title_text = title
    title_width, title_height = get_text_size(draw, title_text, FONT_TITLE)
    title_x = (WIDTH - title_width) // 2
    title_y = 30
    draw.text((title_x, title_y), title_text, font=FONT_TITLE, fill=TEXT_COLOR)

    # --- 表格绘制 ---
    start_y = title_y + title_height + 40
    padding = 10

    # 列宽分配
    col_widths_ratio = [0.15, 0.35, 0.50]
    col_widths = [int(WIDTH * r) for r in col_widths_ratio]

    # 调整最后一列宽度以确保总和为 WIDTH
    col_widths[-1] = WIDTH - sum(col_widths[:-1])

    # 绘制表头
    current_y = start_y
    header_height = get_text_size(draw, "测试", FONT_HEADER)[1]
    row_height_header = header_height + 2 * padding

    # 绘制表头背景
    draw.rectangle([0, current_y, WIDTH, current_y + row_height_header], fill=(240, 240, 240))

    current_x = 0
    for i, header in enumerate(rows[0]):
        draw.text((current_x + padding, current_y + padding), header, font=FONT_HEADER, fill=TEXT_COLOR)
        current_x += col_widths[i]
        draw.line([(current_x, current_y), (current_x, current_y + row_height_header)], fill=(200, 200, 200), width=1)

    draw.line([(0, current_y + row_height_header), (WIDTH, current_y + row_height_header)], fill=(100, 100, 100),
              width=2)
    current_y += row_height_header

    # 绘制数据行
    for row in rows[1:]:

        # 预计算描述列的换行
        desc_lines = wrap_text(draw, row[2], FONT_BODY, col_widths[2] - 2 * padding)

        # 计算行高
        line_height = get_text_size(draw, "测试", FONT_BODY)[1]
        line_spacing = int(line_height * 0.2)

        text_total_height = len(desc_lines) * line_height + (len(desc_lines) - 1) * line_spacing

        # 确保行高至少能容纳一行文本
        min_row_height = line_height + 2 * padding
        row_height = max(min_row_height, text_total_height + 2 * padding)

        # 绘制行背景
        draw.rectangle([0, current_y, WIDTH, current_y + row_height], fill=BACKGROUND_COLOR)

        current_x = 0

        # 绘制第一列 (排名)
        text_x = current_x + padding
        text_y = current_y + (row_height - line_height) // 2
        draw.text((text_x, text_y), row[0], font=FONT_BODY, fill=TEXT_COLOR)
        current_x += col_widths[0]
        draw.line([(current_x, current_y), (current_x, current_y + row_height)], fill=(200, 200, 200), width=1)

        # 绘制第二列 (颜色)
        text_x = current_x + padding
        text_y = current_y + (row_height - line_height) // 2
        draw.text((text_x, text_y), row[1], font=FONT_BODY, fill=TEXT_COLOR)
        current_x += col_widths[1]
        draw.line([(current_x, current_y), (current_x, current_y + row_height)], fill=(200, 200, 200), width=1)

        # 绘制第三列 (描述)
        text_x = current_x + padding
        text_y = current_y + padding
        for line in desc_lines:
            draw.text((text_x, text_y), line, font=FONT_BODY, fill=TEXT_COLOR)
            text_y += line_height + line_spacing

        # 绘制行分隔线
        draw.line([(0, current_y + row_height), (WIDTH, current_y + row_height)], fill=(200, 200, 200), width=1)
        current_y += row_height

    # --- 底部说明 ---
    footer_text = f"数据来源：用户提供 | {title}"
    footer_font = ImageFont.truetype(FONT_PATH, 16)
    footer_width, footer_height = get_text_size(draw, footer_text, footer_font)
    footer_x = (WIDTH - footer_width) // 2
    footer_y = HEIGHT - footer_height - 15

    # 检查表格是否超出底部，如果超出，则不绘制底部说明
    if current_y < HEIGHT - footer_height - 30:
        draw.text((footer_x, footer_y), footer_text, font=footer_font, fill=(100, 100, 100))

    # 保存图片
    img.save(os.path.join(OUTPUT_DIR, file_name))
    print(f"成功生成报告: {file_name}")


# --- 分割数据并生成报告 ---
rows_per_report = 5
total_reports = (len(data) - 1 + rows_per_report - 1) // rows_per_report

for i in range(total_reports):
    start_index = 1 + i * rows_per_report
    end_index = min(1 + (i + 1) * rows_per_report, len(data))

    # 提取表头和当前批次的数据
    report_rows = [data[0]] + data[start_index:end_index]

    title = f"博美犬25种被认可毛色一览表"
    file_name = f"Pomeranian_Colors_Report_{i + 1}_of_{total_reports}.png"

    generate_report_image(title, report_rows, file_name)

# 打包所有报告
import zipfile


with zipfile.ZipFile(ZIP_PATH, 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, _, files in os.walk(OUTPUT_DIR):
        for file in files:
            zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), OUTPUT_DIR))
print(f"报告已打包至: {ZIP_PATH}")
